/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package MainPackage;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;

/**
 *
 * @author leaderpro@gmail.com
 */
public class CarSprite implements Runnable {

    private MyGameCanvas parent;
    private LayerManager manager;
    private Image carImage;
    private Thread runner;
    private int currentCars = 0;
    private int carHits = 0;
    public static final int MAX_CARS = 10;
    private Sprite carSprite = null;

    public CarSprite(MyGameCanvas parent) {
        this.parent = parent;
        this.manager = parent.getManager();
    }
    public int getCarHits(){
        return carHits;
    }
    public void start() throws IOException {
        carImage = Image.createImage("/Images/car.png");
        runner = new Thread(this);
        runner.start();
    }

    public void run() {
        try {
            while (true) {
                randomCar();
                Thread.sleep(500);
            }

        } catch (Exception e) {
        }
    }

    private void randomCar() {
        if (currentCars == MAX_CARS) {
            return;
        }
        carSprite = new Sprite(carImage, 10, 10);
        int randomCarX = parent.getRandom().nextInt(parent.GAME_WIDTH);
        int randomCarY = (parent.BASE - parent.getRandom().nextInt(parent.MAX_HEIGHT + 1) - carSprite.getHeight());
        if (randomCarX < parent.GAME_ORIGIN_X) {
            randomCarX = parent.CENTER_X;
        }
        if (randomCarY < (parent.BASE - parent.MAX_HEIGHT)) {
            randomCarY = parent.CENTER_Y;
        }
        carSprite.setPosition(randomCarX, randomCarY);
        manager.insert(carSprite, 0);
        currentCars++;
    }
    public void checkForColision() throws IOException, MediaException{
        if(manager.getSize()==2)return;
        for (int i = 0; i < manager.getSize()-2; i++) {
            if(parent.getCoupleSprite().collidesWith((Sprite)manager.getLayerAt(i),true)){
                manager.remove(manager.getLayerAt(i));
                currentCars--;
                carHits++;
                playAudio();
            }
        }
    }
    private void playAudio() throws IOException, MediaException{
            InputStream in = getClass().getResourceAsStream("/Audio/ExHit.wav");
            Player play =  Manager.createPlayer(in,"audio/x-wav");
            play.start();
    }
}
